<?php

/**
 * 
 * @author yuxun
 *
 */
class RoutineCrossServerController extends AdminBaseController {

	public function index(){
		$this->setTitle('常规跨服列表');
	
		$filter = new PubFilter();
		$grid   = new PubGrid();
	
		$filter->addFilter('cross_server_name', 'input', '跨服名称');
	
		$params = $filter->get();
		$page = $this->R('page', '1');
		$m = $this->R('m');
		$params['m'] = $m;
		$header = RoutineCrossServerService::indexHeader();
		if(PubFunc::isAjax()){
			$result = RoutineCrossServerService::indexData($params);
			$this->out = array(
					'count'     => $result['count'],
					'data'      => $result['data'],
					'result'    => true
			);
			$this->outType = 'json';
		}else{
			$order  = 'create_time';
			$url = PubFunc::ajaxUrl("?r=routineCrossServer/index", $params);
			$grid->addGrid($header, $url, array(
					'name'=>'数据',
					'order'=>array($order, 'desc'),
					'type'=>'routineCrossServer/index',
					'page'=>$page
			));
	
			$this->out['filter'] = $filter->show();
			$this->out['grid'] = $grid->show();
	
		}
	}
	

    public function add(){
        $this->setTitle('新建常规跨服');
        //(剔除 测试服（测试服需要tab不为0的才可以,测试服tab为0是备选服，备选服可以用）、审核服 )的服务器
        $serverList = RoutineCrossServerService::fitServer();
        
        //查询已经被常规使用的了服
        $useList = RoutineCrossServerService::useServer(0);
        foreach ($serverList as $key=>$val){  //列表只显示还未被使用的服、
        	if(in_array($key, $useList)){
        		unset($serverList[$key]);
        	}
        }        
        
        //查询已经被匹配使用的服
        $matchUserList = MatchCrossServerVService::useServer(0);
        foreach ($serverList as $key=>$val){
        	if(in_array($key, $matchUserList)){
        		unset($serverList[$key]);
        	}
        }
        
        //查询在正式已经存在的匹配跨服服
        $modMatchCrossSer = new ModMatchCrossSer();
        $game = PubBase::getCurrentGame();
        $useServer = $modMatchCrossSer->getAllServer($game);
        $useServerList = array();
        foreach ($useServer as $key=>$val){
        	$useServerList[] = $val['server_id'];
        }
        foreach ($serverList as $key=>$val){
        	if(in_array($key, $useServerList)){
        		unset($serverList[$key]);
        	}
        }
        
        $serverList = array(''=>'请选择') + $serverList;
        $this->out['serverList'] = $serverList;        
        
        //查询跨服预备周期和常规跨服数量限制
        $crossList = SystemService::searchInfo('cross');
        $this->out['crossList'] = $crossList;
    }

    public function doAdd(){
    	$count = RoutineCrossServerService::crepeat(0, 'cross_server_name', $this->R('cross_server_name'),$this->R('g'));
    	if($count > 0){
    		$this->showMessage('名称已经存在');
    	}else{
    		$result = RoutineCrossServerService::doAdd($_POST);
    		
    		if($result !== false){
    			$this->showMessage('新增成功', PubFunc::buildUrl("/oss/?r=routineCrossServer/index"));
    		}else{
    			$this->showMessage('新增失败');
    		}
    	}
    	
        
    }

    public function edit(){
        $id = $this->R('id');
        $info = RoutineCrossServerService::get($id);
        
        if(empty($info)) $this->showMessage('找不到该信息');
        
        $this->setTitle('编辑', $info['cross_server_name']);

        $this->out['info'] = $info;

        $backUrl = PubFunc::buildBackUrl("/oss/?r=routineCrossServer/index");  //返回路径
        $this->out['backUrl'] = $backUrl;
        
        $page = $this->R('page');
        $this->out['page'] = $page;
        
         //(剔除 测试服（测试服需要tab不为0的才可以）、审核服 )的服务器
        $serverList = RoutineCrossServerService::fitServer();
        
        //查询已经被使用的了服
        $useList = RoutineCrossServerService::useServer($id);
        foreach ($serverList as $key=>$val){  //列表只显示还未被使用的服
        	if(in_array($key, $useList)){
        		unset($serverList[$key]);
        	}
        }
        
        //查询已经被匹配使用的服
        $matchUserList = MatchCrossServerVService::useServer(0);
        foreach ($serverList as $key=>$val){
        	if(in_array($key, $matchUserList)){
        		unset($serverList[$key]);
        	}
        }
        
        //查询在正式已经存在的匹配跨服服
        $modMatchCrossSer = new ModMatchCrossSer();
        $game = PubBase::getCurrentGame();
        $useServer = $modMatchCrossSer->getAllServer($game);
        $useServerList = array();
        foreach ($useServer as $key=>$val){
        	$useServerList[] = $val['server_id'];
        }
        foreach ($serverList as $key=>$val){
        	if(in_array($key, $useServerList)){
        		unset($serverList[$key]);
        	}
        }
        
        //if(count($info['item']) == 0){
        	$serverList = array(''=>'请选择') + $serverList;
        //}
        $this->out['serverList'] = $serverList;
        
        //查询跨服预备周期和常规跨服数量限制
        $crossList = SystemService::searchInfo('cross');
        $this->out['crossList'] = $crossList;
    }

    public function doEdit(){
        $id = $this->R('id');
        $count = RoutineCrossServerService::crepeat($this->R('id'), 'cross_server_name', $this->R('cross_server_name'),$this->R('g'));
        if($count > 0){
        	$this->showMessage('名称已经存在');
        }else{
        	$result = RoutineCrossServerService::doEdit($id, $_POST);
        	
            if($result['state'] !== false){
        		$this->showMessage('编辑成功', PubFunc::buildBackUrl("/oss/?r=routineCrossServer/index"));
        	}else{
        		$this->showMessage('编辑失败');
        	}
        }
        
    }
    
    public function delete(){
    	$id = $this->R('id');
    	if($this->isAuth !=1){  //isAuth为1则没有权限
    		$result = RoutineCrossServerService::delete($id);
    		if($result !== false){
    			$this->showMessage('删除成功', PubFunc::buildBackUrl("/oss/?r=routineCrossServer/index"));
    		}else{
    			$this->showMessage('删除失败', PubFunc::buildBackUrl("/oss/?r=routineCrossServer/index"));
    		}
    	}
    }
    
    /**
     * 解除
     */
    public function relieve(){
    	$ids = PubRequest::R('ids');
    	if($ids == ''){
    		$out = array('status'=>0,'msg'=>'请选择要操作的数据','data'=>'');
    	}else{
    		$out = RoutineCrossServerService::relieve($ids);
    	}
    	 
    	$this->out = $out;
    	$this->outType = 'json';
    }
    
    /**
     * 强制性解除
     */
    public function forcerelieve(){
    	$ids = PubRequest::R('ids');
    	if($ids == ''){
    		$out = array('status'=>0,'msg'=>'请选择要操作的数据','data'=>'');
    	}else{
    		$out = RoutineCrossServerService::forcerelieve($ids);
    	}
    	
    	$this->out = $out;
    	$this->outType = 'json';
    }
    
    /**
     * 查看强制性解除记录
     */
    public function forceView(){
    	$this->layout = '';
    
    	$grid   = new PubGrid();
    	$filter = new PubFilter();
    	$filter->addFilter('cross_server_name', 'input', '跨服名称');
    
    	$params = $filter->get();
    	$header = RoutineCrossServerService::forceViewHeader();
    	$data = RoutineCrossServerService::forceView($params);
    	$grid->addGrid($header, $data);
    	
    	$this->out['fiter_special'] = 1;
    	$this->out['filter'] = $filter->show();
    	$this->out['grid'] = $grid->show();

    }
    
    
    /**
     * 同步
     */
    public function rouSynchro(){
    	$ids = PubRequest::R('ids');
    	if($ids == ''){
    		$out = array('status'=>0,'msg'=>'请选择要操作的数据','data'=>'');
    	}else{
    		$out = RoutineCrossServerService::rouSynchro($ids);
    	}
    	
    	$this->out = $out;
    	$this->outType = 'json';
    }
    
    /**
     * 自动将常规跨服转化为匹配跨服
     * 定时任务，先查询重置时间，如果当前时间是重置时间的前3天，则自动转化
     * 
     */
    public function automatic(){
    	//查询重置时间
    	$game = 'mango';
    	$crossList = SystemService::searchInfo('cross');
    	$reset_time = $crossList['reset_time'];
    	$reset_time = strtotime ("-3 day", strtotime($reset_time));
    	
    	$nowTime = strtotime(date('Y-m-d H:i:00',time()));  //当前时间
//     	echo $reset_time;echo'<br/>';echo $nowTime;echo'<br/>';
//     	echo date('Y-m-d H:i:00',$reset_time);echo'<br/>';echo date('Y-m-d H:i:00',$nowTime);echo'<br/>';
    	if($reset_time == $nowTime){
    		//获取符合规定的服务器加入匹配行列中
    		//常规跨服的服务器（结束时间在当前时间之前的可以加入匹配行列中（要踢出未开服的服））
    		//匹配跨服的服务器（所有加进来）
    		$modRoutineCrossCerver = new ModRoutineCrossCerver();
    		$routineList = $modRoutineCrossCerver->getAddMatchServer($nowTime,$game);
   
    		$server_ids = '';
    		$fRoutineList = array(); //符合进入匹配行列的常规跨服数据
    		$cerver_ids = '';  //符合进入匹配行列的常规跨服数据主键id，要用来删除关系
    		foreach ($routineList as $key=>$val){
    			$cerver_ids .= $val['id'] . ', ';
    			$server_ids .= $val['server_id'] . ', ';
    			$fRoutineList[$val['server_id']] = $val;
    		}
    		$cerver_ids = substr($cerver_ids,0,strlen($cerver_ids)-2);
    		
    		$server_ids = substr($server_ids,0,strlen($server_ids)-2);
    		$modServerChannel = new ModServerChannel();
    		if($server_ids != ''){
    			$serverChannelList = $modServerChannel->selectChannel($server_ids, $game);
    			foreach ($serverChannelList as $key=>$val){  //如果是备选服这unset(tab=0)
    				if($val['tab'] == 0){
    					unset($fRoutineList[$val['server_id']]);
    				}
    			}
    		}
    		
    		$modMatchCrossSer = new ModMatchCrossSer();
    		$modMatchCrossServer = new ModMatchCrossServer();
    		$fmatchList = $modMatchCrossServer->getAddMatchServer($game); //符合进入匹配行列匹配跨服数据   

    		//查询在常规跨服的服务器（结束时间在当前时间之后的可以加入匹配行列中（要踢出未开服的服））
    		$delRoutineList = $modRoutineCrossCerver->getdelMatchServer($nowTime,$game);
    		$delRoutineList_array = array();
    		foreach ($delRoutineList as $key=>$val){
    			$delRoutineList_array[] = $val['server_id'];
    		}
    		
    		//还需要剔除已经使用的匹配跨服数据中存在常规跨服的数据
    		foreach($fmatchList as $key=>$val){
    			if(in_array($val['server_id'], $delRoutineList_array)){
    				unset($fmatchList[$key]);
    			}
    		}

    		$fserver_ids = '';  //最终符合规定的服务器ids
    		$routine_cross_ss_ids = ''; //常规跨服的服数据加入之后匹配跨服之后需要删除的关系
    		foreach ($fRoutineList as $key=>$val){
    			$fserver_ids .= $val['server_id'] . ', ';
    			$routine_cross_ss_ids .= $val['id'] . ', ';
    		}
    		foreach ($fmatchList as $key=>$val){
    			$fserver_ids .= $val['server_id'] . ', ';
    		}
    		$fserver_ids = substr($fserver_ids,0,strlen($fserver_ids)-2);
    		$routine_cross_ss_ids = substr($routine_cross_ss_ids,0,strlen($routine_cross_ss_ids)-2);
    		
    		if($fserver_ids == ''){
    			echo "不存在符合规定的匹配数据 \n";
    			exit;
    		}
    		
    		//查询服务器的信息，目前先将按各服的开服时间作为排序
    		$modServer = new ModServer();
    		$fserverList = $modServer->getOrderServerForIds($game, $fserver_ids);
    		
    		$match_automatic_num = $crossList['match_automatic_num'];  //每一组的匹配跨服最大服务器个数
    		$match_cross = array();
    		$d = array();
    		$l = count($fserverList);
    		//根据配置的匹配跨服自动数量限制进行分组
    		foreach ($fserverList as $key=>$val){ 
    			$n = $key + 1;
    			if($n % $match_automatic_num == 0){
    				$d[] = $val['id'];
    				$match_cross[] = $d;
     				$d = array();
    			}else{
    				$d[] = $val['id'];
    				if($n == $l){
    					$match_cross[] = $d;
    				}
    			}  			
    		}

    		//将分组配置到各个匹配跨服，再保存到临时的匹配跨服表和关系表
    		//临时的匹配跨服表和关系表每次生效之后都要清空，查询到若有数据，则先删除
    		$modMatchCrossServer_v = new ModMatchCrossServerV();
    		$v_obj = $modMatchCrossServer_v->findAllByAttributes(array('game'=>$game));
    		if($v_obj){
    			//存在数据则删除
    			foreach ($v_obj as $key=>$val){
    				$modMatchCrossServerV = new ModMatchCrossServerV();
    				$modMatchCrossServerV->deleteByPk($val['id']);
    				
    				//删除常规跨服服务器与服务器的关系
    				$modMatchCrossSerV = new ModMatchCrossSerV();
    				$modMatchCrossSerV->deleteAll('match_id=:match_id', array(':match_id'=>$val['id']));
    			}
    		}
    		//获取匹配跨服的配置 和 常规跨服 的配置
    		$modMatchCrossServer = new ModMatchCrossServer();
    		$setMatchList = $modMatchCrossServer->findAllByAttributes(array('game'=>$game,'is_delete'=>0));
    		$set_array = array();
    		foreach ($setMatchList as $key=>$val){
    			$sd = array();
    			$sd['node_name'] = $val->node_name;
    			$sd['ip'] = $val->ip;
    			$sd['port'] = $val->port;
    			$sd['version'] = $val->version;
    			$sd['develop_id'] = $val->develop_id;
    			array_push($set_array, $sd);
    		}
    		
    		$modRoutineCrossCerver = new ModRoutineCrossCerver();
    		$setRoutineList = $modRoutineCrossCerver->findAllByAttributes(array('game'=>$game));
    		foreach ($setRoutineList as $key=>$val){
    			$sd = array();
    			$sd['node_name'] = $val->node_name;
    			$sd['ip'] = $val->ip;
    			$sd['port'] = $val->port;
    			$sd['version'] = $val->version;
    			$sd['develop_id'] = $val->develop_id;
    			array_push($set_array, $sd);
    		}
    		
    		$modMatchCrossSer_v = new ModMatchCrossSerV();
    		$march_server_v = array();
    		foreach ($match_cross as $key=>$val){
    			if(isset($set_array[$key])){  //存在
    				$node_name = $set_array[$key]['node_name'];
    				$ip = $set_array[$key]['ip'];
    				$port = $set_array[$key]['port'];
    				$version = $set_array[$key]['version'];
    				$develop_id = $set_array[$key]['develop_id'];
    			}else{
    				$node_name = '';
    				$ip ='';
    				$port = '';
    				$version = '';
    				$develop_id = '';
    			}
    		
    			$modMatchCrossServer_v = new ModMatchCrossServerV();
    			$modMatchCrossServer_v->game = $game;
    			$modMatchCrossServer_v->cross_server_name = '匹配跨服'.$key;
    			$modMatchCrossServer_v->node_name = $node_name;
    			$modMatchCrossServer_v->ip = $ip;
    			$modMatchCrossServer_v->port = $port;
    			$modMatchCrossServer_v->version = $version;
    			$modMatchCrossServer_v->develop_id = $develop_id;
    			$modMatchCrossServer_v->create_user   = 1;
    			$modMatchCrossServer_v->create_time   = time();
    			$modMatchCrossServer_v->update_user   = 1;
    			$modMatchCrossServer_v->update_time   = time();
    			$modMatchCrossServer_v->save();
    			$match_id = $modMatchCrossServer_v->id;
    			foreach ($val as $k=>$v){
    				$d = array();
    				$d['server_id'] = $v;
    				$d['match_id'] = $match_id;
    				array_push($march_server_v, $d);
    			}
    		}
    		$modMatchCrossSer_v->addmuch($march_server_v);
    		 
    		//抽空那些已经从常规跨服到匹配跨服的数据
    		$modRoutineCrossSer = new ModRoutineCrossSer();
    		if($cerver_ids != ''){
    			$modRoutineCrossSer->deleteForIds($cerver_ids);
    		}    		
    		echo "匹配跨服配置自动生成成功 \n";

    	}else{
    		echo "暂未到重置时间的前3天 \n";
    	}

    	exit;
    }
    
    public function show(){
    	$this->setTitle('跨服服务器列表');
    	$grid   = new PubGrid();
    	$params = array();
    	$data = RoutineCrossServerService::send($params,3);
    	if($data['status'] == 1){
    		$list = $data['data']['cross_net_data']['net_data'];
    		$show = array();
    		foreach ($list as $key=>$val){
    			$d = array();
    			$d['version'] = $val['version'];
    			$d['crossnode'] = $val['crossnode'];
    			$gamenodes  = implode(',', $val['gamenodes']);
    			$d['gamenodes'] = $gamenodes;
    			$d['ip'] = $val['extend_data']['ip'];
    			$d['port'] = $val['extend_data']['port'];
    			array_push($show, $d);
    		}
//     		echo '<pre/>';
//     		var_dump($show);exit;
    		
    		$header = RoutineCrossServerService::sHeader();
    		$grid->addGrid($header, $show);
    		$this->out['grid'] = $grid->show();
    	}else{
    		$this->out['state'] = -1;
    		$this->out['msg'] = $data['msg'];
    	}
    }
    
}